'''
    @project: Masdevallia
    @author: Austin Baker
    @created: 2/22/2014
    @license: http://opensource.org/licenses/mit-license.php

    The MIT License (MIT)

    Copyright (c) 2014 Austin Baker
    
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
    
    About:
    Class for manipulating matrices.
'''

'''
============================================================
--->>   IMPORT MODULES
============================================================
'''
import maya.OpenMaya as OM
import masdevallia.utility.Dag as Dag

'''
============================================================
--->>   MATRIX CLASS
============================================================
'''
class Matrix( object ):
    '''
    Class for getting and manipulating a matrix.
    
    @inObjName: String. Name of object with the matrix.
    @matrixType: String. Valid types are listed in self.matrixTypes.
    '''
    def __new__( cls, inObjName, inMatrixType ):
        #print '__new__inObjName, inMatrixType: {0}, {1}'.format( inObjName, inMatrixType )
        if isinstance( inMatrixType, str ) and isinstance( inObjName, str ):
            matrixTypes = ['matrix', 'inverseMatrix', 'parentInverseMatrix',
                            'parentMatrix', 'worldInverseMatrix', 'worldMatrix',
                            'xformMatrix']
            validMatrixType = [m for m in matrixTypes if inMatrixType == m]
            if validMatrixType:
                return super( Matrix, cls ).__new__( cls, inObjName, inMatrixType )
            else:
                raise RuntimeError( 'inMatrixType is not a valid type. {0}'.format( inMatrixType ) )
        else:
            if not isinstance( inMatrixType, str ):
                raise RuntimeError( 'inMatrixType is not a string. {0}'.format( type(inMatrixType) ) )
            if not isinstance( inObjName, str ):
                raise RuntimeError( 'inObjName is not a string. {0}'.format( type(inObjName) ) )
    
    def __init__( self, inObjName, inMatrixType ):
        self.objectName = inObjName
        self.objectSpace = OM.MSpace.kObject
        self.postSpace = OM.MSpace.kPostTransform
        self.preSpace = OM.MSpace.kPreTransform
        self.tranSpace = OM.MSpace.kTransform
        self.worldSpace = OM.MSpace.kWorld        
        self.matrixTypes = {'matrix':self.objectSpace,
                            'inverseMatrix':self.objectSpace,
                            'parentInverseMatrix':self.objectSpace,
                            'parentMatrix':self.objectSpace,
                            'worldInverseMatrix':self.worldSpace,
                            'worldMatrix':self.worldSpace,
                            'xformMatrix':self.tranSpace}
        self.matrixSpace = self.matrixTypes[ inMatrixType ]
        self.matrix = Dag.getObjMatrix( inObjName, inMatrixType )
        self.transformMatrix = OM.MTransformationMatrix( self.matrix )

    def setMatrix( self, inMatrix ):
        path = Dag.getDagPath( self.objectName )
        transFn = OM.MFnTransform( path )
        transFn.set( OM.MTransformationMatrix( inMatrix ) )
        
    def getTranslation( self ):
        return OM.MTransformationMatrix( self.matrix ).getTranslation( self.matrixSpace )

    def setTranslation( self, inMVector ):
        if isinstance( inMVector, OM.MVector ):
            #OM.MTransformationMatrix( self.matrix ).setTranslation( inMVector, self.matrixSpace )
            OM.MFnTransform( Dag.getDagPath( self.objectName ) ).setTranslation( inMVector, self.matrixSpace )
        else:
            raise RuntimeError( 'inMVector is not a MVector. {0}'.format( type(inMVector) ) )
    
    def translateBy( self, inMVector, inSpace ):
        if isinstance( inMVector, OM.MVector ):
            OM.MFnTransform( Dag.getDagPath( self.objectName ) ).translateBy( inMVector, inSpace )
        else:
            raise RuntimeError( 'inMVector is not a MVector. {0}'.format( type(inMVector) ) )
    
    def getRotation( self, inRotType ):
        if inRotType == OM.MEulerRotation:
            return OM.MTransformationMatrix( self.matrix ).eulerRotation()
        elif inRotType == OM.MQuaternion:
            return OM.MTransformationMatrix( self.matrix ).rotation()
        else:
            raise RuntimeError( 'inRotType is {0}. Valid types are "euler" and "quat".'.format( inRotType ) )
    
    def setRotation( self, inRotation ):
        if isinstance( inRotation, OM.MEulerRotation ) or isinstance( inRotation, OM.MQuaternion ):
            OM.MFnTransform( Dag.getDagPath( self.objectName ) ).setRotation( inRotation )
        else:
            raise RuntimeError( 'inRotation is not a MEulerRotation or MQuaternion. {0}'.format( type(inRotation) ) )
    
    def rotateBy( self, inRotation ):
        if isinstance( inRotation, OM.MEulerRotation ) or isinstance( inRotation, OM.MQuaternion ):
            OM.MFnTransform( Dag.getDagPath( self.objectName ) ).rotateBy( inRotation )
        else:
            raise RuntimeError( 'inRotation is not a MEulerRotation or MQuaternion. {0}'.format( type(inRotation) ) )
        
    def rotationOrder( self ):
        return OM.MFnTransform( Dag.getDagPath( self.objectName ) ).rotationOrder()
    
    def setRotationOrder( self, inRotOrder=OM.MTransformationMatrix.kXYZ ):
        OM.MFnTransform( Dag.getDagPath( self.objectName ) ).setRotationOrder( inRotOrder, True )
        
    def getScale( self ):
        util = OM.MScriptUtil()
        util.createFromDouble(0.0, 0.0, 0.0)
        ptr = util.asDoublePtr()
        OM.MTransformationMatrix( self.matrix ).getScale( ptr, self.matrixSpace )
        scale = [OM.MScriptUtil().getDoubleArrayItem( ptr, 0 ),
                 OM.MScriptUtil().getDoubleArrayItem( ptr, 1 ),
                 OM.MScriptUtil().getDoubleArrayItem( ptr, 2 )]
        return scale
    
    def setScale( self, inScale ):
        if isinstance( inScale, list ):
            if len( inScale ) == 3:
                util = OM.MScriptUtil()
                util.createFromDouble( inScale[0], inScale[1], inScale[2] )
                ptr = util.asDoublePtr()
                OM.MFnTransform( Dag.getDagPath( self.objectName ) ).setScale( ptr )
            else:
                raise RuntimeError( 'inScale must have a length of 3.' )
        else:
            raise RuntimeError( 'inScale is not a list. {0}'.format( type( inScale ) ) )
                
    def mirror( self, inMirrorAxis=0, inOrientAxis=0 ):
        '''
        Mirrors the matrix around it's parent.
        
        @inMirrorAxis: Int. The axis to mirror the matrix across.
        @inOrientAxis: Int. The axis to mirror the orientation across.
          x y z
        x 1 0 0 0
        y 0 1 0 0
        z 0 0 1 0
          0 0 0 1
        '''
        origMatrix = Dag.getObjMatrix( self.objectName, 'matrix' )
        mirrorMatrix = origMatrix
        
        orientAxes = [0,1,2]
        orientAxes.remove( inOrientAxis )
        orientAxisB = orientAxes[0]
        orientAxisC = orientAxes[1]
        
        '''
        Flip all the axes in the mirrorMatrix. 
        Example: inMirrorAxis=0(x) and inOrientAxis=0(x)
          x y z
        x 1 0 0 0
        y B 1 0 0
        z C 0 1 0
          0 0 0 1
        '''
        # Multiplies by -1 the value at matrix[orientAxisB][inMirrorAxis] and sets the corresponding
        # [row][col] in mirrorMatrix to the resulting value.
        newValue = OM.MScriptUtil.getDoubleArrayItem( origMatrix[ orientAxisB ], inMirrorAxis ) * -1
        OM.MScriptUtil.setDoubleArray( mirrorMatrix[ orientAxisB ], inMirrorAxis, newValue )
        # Multiplies by -1 the value at matrix[orientAxisC][inMirrorAxis] and sets the corresponding
        # [row][col] in mirrorMatrix to the resulting value.
        newValue = OM.MScriptUtil.getDoubleArrayItem( origMatrix[ orientAxisC ], inMirrorAxis ) * -1
        OM.MScriptUtil.setDoubleArray( mirrorMatrix[ orientAxisC ], inMirrorAxis, newValue )
        
        '''
        The above flips all the axes resulting in a change of handedness, so we flip one of the axes back.
        Example: inMirrorAxis=0(x) and inOrientAxis=0(x)
          x y z
        x 1 B C 0
        y 0 1 0 0
        z 0 0 1 0
          0 0 0 1
        '''
        mirrorAxes = [0,1,2]
        mirrorAxes.remove( inMirrorAxis )
        mirrorAxisB = mirrorAxes[0]
        mirrorAxisC = mirrorAxes[1]
        # Multiplies by -1 the value at matrix[inOrientAxis][mirrorAxisB] and sets the corresponding
        # [row][col] in mirrorMatrix to the resulting value.
        newValue = OM.MScriptUtil.getDoubleArrayItem( mirrorMatrix[ inOrientAxis ], mirrorAxisB ) * -1
        OM.MScriptUtil.setDoubleArray( mirrorMatrix[ inOrientAxis ], mirrorAxisB, newValue )
        # Multiplies by -1 the value at matrix[inOrientAxis][mirrorAxisC] and sets the corresponding
        # [row][col] in mirrorMatrix to the resulting value.
        newValue = OM.MScriptUtil.getDoubleArrayItem( mirrorMatrix[ inOrientAxis ], mirrorAxisC ) * -1
        OM.MScriptUtil.setDoubleArray( mirrorMatrix[ inOrientAxis ], mirrorAxisC, newValue )
        
        '''
        Mirror the translation by multiplying the original matrix[3][inMirrorAxis] by -1
        then set the corresponding row/col in the mirror matrix to the resulting value.
        Example: inMirrorAxis=0(x) and inOrientAxis=0(x)
          x y z
        x 1 0 0 0
        y 0 1 0 0
        z 0 0 1 0
          N 0 0 1
        '''
        newValue = OM.MScriptUtil.getDoubleArrayItem( origMatrix[ 3 ], inMirrorAxis ) * -1
        OM.MScriptUtil.setDoubleArray( mirrorMatrix[ 3 ], inMirrorAxis, newValue )
        
        # Apply the new matrix.
        MFnTrans = OM.MFnTransform( Dag.getDagPath( self.objectName ) )
        MFnTrans.set( OM.MTransformationMatrix( mirrorMatrix ) )
        
    def rotationMatrix( self ):
        return OM.MTransformationMatrix( self.matrix ).asRotateMatrix()
        
    def getMatrixAsList( self ):
        listMatrix = []
        for row in range(0,4):
            for cell in range(0,4):
                listMatrix.append( OM.MScriptUtil.getDoubleArrayItem( self.matrix[row], cell ) )
        return listMatrix
    
    def printMatrix( self ):
        listMatrix = self.getMatrixAsList()
        print listMatrix[0], listMatrix[1], listMatrix[2], listMatrix[3]
        print listMatrix[4], listMatrix[5], listMatrix[6], listMatrix[7]
        print listMatrix[8], listMatrix[9], listMatrix[10], listMatrix[11]
        print listMatrix[12], listMatrix[13], listMatrix[14], listMatrix[15]